package mr.go.yaxc.actions;

import java.util.ArrayList;
import java.util.Map;

import mr.go.yaxc.Action;
import mr.go.yaxc.ConfigurationError;
import mr.go.yaxc.ScopeHandler;

import org.xml.sax.Attributes;

/**
 * This action creates a new entry in map passed as <i>property</i>. Used with
 * {@link CreateMap}
 * 
 * <h6>on xml element start:</h6> Obtains <i>property</i> 'map' with a map
 * reference and sets <i>params</i> <h6>on xml element end:</h6> creates map
 * entry using <i>params</i> (the first param is a key, the second is a value).
 * Reports error if there are more than two params. If successfull, sets
 * <i>property</i> 'object' <h6>prerequisites:</h6> <i>property</i> 'map' in
 * scope <h6>attributes:</h6> none
 *<p>
 * Example:<br>
 * 
 * <pre>
 * &lt;Map&gt;
 * 				&lt;Entry&gt;
 * 					&lt;String&gt;name1&lt;/String&gt;
 * 					&lt;Integer&gt;0&lt;/Integer&gt;
 * 				&lt;/Entry&gt;
 * 				&lt;Entry&gt;
 * 					&lt;String&gt;name2&lt;/String&gt;
 * 					&lt;Integer&gt;1&lt;/Integer&gt;
 * 				&lt;/Entry&gt;
 * 			&lt;/Map&gt;
 * </pre>
 * 
 * </p>
 * 
 * 
 * @author Marcin Rzeźnicki
 * 
 */
public class CreateMapEntry extends Action {

    private Map<Object, Object> map;

    @Override
    public void carryOut(String name, Attributes attributes,
                         ScopeHandler handler)
            throws Exception {
        map = (Map<Object, Object>) handler.getParentProperty("map");
        if (map == null) {
            throw new ConfigurationError("No map in context");
        }
        params = new ArrayList<Object>(2);
    }

    @Override
    public void processed(String body, ScopeHandler handler)
            throws Exception {
        if (params.size() != 2) {
            throw new ConfigurationError(
                    "Wrong number of parameters (must be 2)");
        }
        map.put(params.get(0),
                params.get(1));
    }
}
